Little changes on Colombian Programming Contest solutions.
[and.git] / 12321 - Gas Stations / 12321.2.cpp
blobe4551a2108e58860125022ae907d7f7c9e176beb
1 using namespace std;
2 #include <algorithm>
3 #include <iostream>
4 #include <iterator>
5 #include <numeric>
6 #include <sstream>
7 #include <fstream>
8 #include <cassert>
9 #include <climits>
10 #include <cstdlib>
11 #include <cstring>
12 #include <string>
13 #include <cstdio>
14 #include <vector>
15 #include <cmath>
16 #include <queue>
17 #include <deque>
18 #include <stack>
19 #include <list>
20 #include <map>
21 #include <set>
23 #define foreach(x, v) for (typeof (v).begin() x=(v).begin(); x !=(v).end(); ++x)
24 #define For(i, a, b) for (int i=(a); i<(b); ++i)
25 #define D(x) cout << #x " is " << x << endl
27 const int MAXN = 10010;
28 pair<int, int> g[MAXN];
29 int places[2 * MAXN];
30 int best[2 * MAXN];
32 bool compare(const pair<int, int> &a, const pair<int, int> &b) {
33 if (a.first != b.first) return a.first < b.first;
34 return a.second > b.second;
37 int main(){
38 int n;
39 long long L;
40 while (scanf("%lld %d", &L, &n) == 2) {
41 if (L == 0 and n == 0) break;
42 int P = 0;
43 places[P++] = 0;
44 for (int i = 0; i < n; ++i) {
45 long long x, r; scanf("%lld %lld", &x, &r);
46 g[i].first = max(0LL, x - r);
47 g[i].second = min(L, x + r);
48 places[P++] = g[i].first;
49 places[P++] = g[i].second;
51 places[P++] = L;
52 sort(places, places + P);
53 P = unique(places, places + P) - places;
55 for (int i = 0; i < n; ++i) {
56 g[i].first = lower_bound(places, places + P, g[i].first) - places;
57 g[i].second = lower_bound(places, places + P, g[i].second) - places;
60 //sort(g, g + n, compare);
61 // for (int i = 0; i < n; ++i) {
62 // printf("<%d, %d>\n", g[i].first, g[i].second);
63 // }
65 for (int i = 0; i < P; ++i) {
66 best[i] = -1;
68 for (int i = 0; i < n; ++i) {
69 best[g[i].first] = max(best[g[i].first], g[i].second);
71 for (int i = 1; i < P; ++i) {
72 best[i] = max(best[i], best[i-1]);
75 // for (int i = 0; i < P; ++i) {
76 // printf("best[%d] = %d\n", i, best[i]);
77 // }
80 if (g[0].first < 0) {
81 puts("-1");
82 continue;
84 int ans = 0;
85 int cur = 0;
86 int end = lower_bound(places, places + P, L) - places;
87 while (cur < end and cur < best[cur]) {
88 ans++;
89 cur = best[cur];
91 if (cur < end) {
92 puts("-1");
93 } else {
94 assert(ans <= n);
95 printf("%d\n", n - ans);
98 return 0;